<script setup lang="ts">
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import { FetchSensor } from "@/service/getData"

import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {ref, onMounted, onUnmounted} from 'vue'
import {parseGeoJSON} from "echarts";

// 注册必须的组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
])

const { FetchList } = FetchSensor();
const token = localStorage.getItem("token");

const chartData = ref([])

// CO2图表配置
const co2Option = ref({
  title: {
    text: 'CO₂ 浓度变化',
    textStyle: { color: '#fff' }
  },
  tooltip: {
    trigger: 'axis',
    formatter: (params: any) => {
      const data = params[0]
      return `${data.name}<br/>CO₂: ${data.value.toFixed(0)} ppm`
    }
  },
  grid: {
    top: '25%',
    left: '3%',
    right: '4%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: chartData.value.map(item => item.time),
    axisLabel: { color: '#fff' },
    axisLine: { lineStyle: { color: '#fff' } }
  },
  yAxis: {
    type: 'value',
    name: 'CO₂ (ppm)',
    nameTextStyle: { color: '#fff' },
    axisLabel: { color: '#fff' },
    axisLine: { lineStyle: { color: '#fff' } },
    splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
  },
  series: [{
    type: 'line',
    smooth: true,
    data: chartData.value.map(item => item.co2),
    itemStyle: { color: '#00ffff' },
    areaStyle: {
      color: {
        type: 'linear',
        x: 0, y: 0, x2: 0, y2: 1,
        colorStops: [
          { offset: 0, color: 'rgba(0,255,255,0.3)' },
          { offset: 1, color: 'rgba(0,255,255,0.1)' }
        ]
      }
    }
  }],
  dataZoom: [{
    type: 'inside',
    start: 0,
    end: 100
  }]
})

// 温度图表配置
const tempOption = ref({
  title: {
    text: '土壤温度变化',
    textStyle: { color: '#fff' }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' },
    formatter: (params: any) => {
      const data = params[0]
      return `${data.name}<br/>温度: ${data.value.toFixed(1)}°C`
    }
  },
  grid: {
    top: '25%',
    left: '3%',
    right: '4%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: chartData.value.map(item => item.time),
    axisLabel: { color: '#fff' },
    axisLine: { lineStyle: { color: '#fff' } }
  },
  yAxis: {
    type: 'value',
    name: '温度 (°C)',
    nameTextStyle: { color: '#fff' },
    axisLabel: {
      color: '#fff',
      formatter: '{value} °C'
    },
    axisLine: { lineStyle: { color: '#fff' } },
    splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
  },
  series: [{
    type: 'bar',
    data: chartData.value.map(item => item.temp),
    itemStyle: {
      color: {
        type: 'linear',
        x: 0, y: 0, x2: 0, y2: 1,
        colorStops: [
          { offset: 0, color: '#ff6e76' },
          { offset: 1, color: '#eb2f96' }
        ]
      },
      borderRadius: [4, 4, 0, 0]
    },
    barWidth: '60%'
  }],
  dataZoom: [{
    type: 'inside',
    start: 0,
    end: 100
  }]
})


const init = async () => {
  try {
    const response = await FetchList(token);
    const data = [];
    for (let i=0; i < response["time"].length; i++){
      const timestamp = response["time"][i]; // 示例时间戳
      const time = new Date(timestamp);
      const formattedTime = time.toLocaleTimeString('zh', { hour: '2-digit', minute: '2-digit' });
      const temp = response["temp"][i];
      const co2 = response["co2"][i];
      data.push({
        time: formattedTime,
        co2: co2,
        temp: temp
      })
    }
    chartData.value = data;

    // 更新图表配置
    co2Option.value.xAxis.data = chartData.value.map(item => item.time);
    co2Option.value.series[0].data = chartData.value.map(item => item.co2);

    tempOption.value.xAxis.data = chartData.value.map(item => item.time);
    tempOption.value.series[0].data = chartData.value.map(item => item.temp);

  } catch (error) {
    console.error('获取数据失败:', error);
  }
};
onMounted(() => {
  init();
})

</script>

<template>
  <div class="charts-container">
    <!-- CO2折线图 -->
    <div class="chart-box">
      <v-chart class="chart" :option="co2Option" autoresize />
    </div>

    <!-- 土壤温度柱状图 -->
    <div class="chart-box">
      <v-chart class="chart" :option="tempOption" autoresize />
    </div>
  </div>
</template>

<style scoped>
.charts-container {
  width: 100%;
  height: 600px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background-color: #1a1a1a;
  border-radius: 8px;
}

.chart-box {
  flex: 1;
  min-height: 0; /* 重要：防止flex子项溢出 */
}

.chart {
  width: 100%;
  height: 100%;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .charts-container {
    height: 800px;
  }
}
</style>